﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;
using Lm.Common.Auth.Account;

namespace Lm.Common.Auth.Token
{
    [Operation.Operation("{BEC2DB9E-5290-4018-A951-BC8BF8639F22}", "临时授权", "")]
    public class TempAuthorize : Operation.OperationBase
    {
        static TempAuthorize()
        { Operation.OperationBase.CreateOperation(typeof(TempAuthorize)); }

        public TempAuthorize(string token)
            : base(token)
        { }

        public void Authorize(string targetUserAccount, DateTime expiresTime)
        {
            if (this.Token.OperatorAccount != this.Token.OwnerAccount)
            { throw new Exception("使用他人授权登录时，不能进行临时授权操作"); }
            if (targetUserAccount.IsNullOrBlank())
            { throw new Exception("被授权帐号不能为空"); }
            if (expiresTime <= DateTime.Now)
            { throw new Exception("临时授权到期时间比当前时间小"); }
            using (var tran = new System.Transactions.TransactionScope())
            {
                var currentAccount = new AccountDal().GetByUserId(this.Token.OwnerAccount);
                if (currentAccount.UserAccount == targetUserAccount)
                { throw new Exception("不能对自己进行临时授权"); }
                var targetAccount = new AccountDal().GetByUserAccount(targetUserAccount);
                if (targetAccount.GetStatus() != Model.RoleStatus.Live)
                { throw new Exception("被授权帐号不是可用状态"); }
                if (DAL.DALFactory.Create().Insert<Model.Token>(new Model.Token()
                {
                    CreateTime = DateTime.Now,
                    ExpireTime = expiresTime,
                    Id = Guid.NewGuid(),
                    OperatorAccount = targetAccount.Id,
                    OwnerAccount = currentAccount.Id,
                    UserToken = Guid.NewGuid().ToString("n")
                }) == false)
                { throw new Exception("临时授权失败"); }
                tran.Complete();
            }
        }

        public List<Model.Token> GetAuthorizeList(params System.Linq.Expressions.Expression<Func<Model.Token,bool>>[] conditions)
        {
            if (this.Token.OwnerAccount != this.Token.OperatorAccount)
            { throw new Exception("使用他人临时授权登录时，不能查询临时授权"); }
            var conditionList=conditions.ToList();
            conditionList.Add(t=>t.OwnerAccount==this.Token.OwnerAccount);
            conditionList.Add(t => t.OwnerAccount != t.OperatorAccount);
            return DAL.DALFactory.Create().Select<Model.Token>(conditionList.ToArray());
        }

        public List<Model.Token> GetReceivedAuthorizeList(params System.Linq.Expressions.Expression<Func<Model.Token, bool>>[] conditions)
        {
            if (this.Token.OwnerAccount != this.Token.OperatorAccount)
            { throw new Exception("使用他人临时授权登录时，不能查询临时授权"); }
            var conditionList = conditions.ToList();
            conditionList.Add(t => t.OperatorAccount == this.Token.OwnerAccount);
            conditionList.Add(t => t.OwnerAccount != t.OperatorAccount);
            return DAL.DALFactory.Create().Select<Model.Token>(conditionList.ToArray());
        }

        public void StopAuthorize(string userToken)
        {
            if (this.Token.OwnerAccount != this.Token.OperatorAccount)
            { throw new Exception("使用他人临时授权登录时，不能终止临时授权"); }

            if (userToken.IsNullOrBlank())
            { throw new Exception("必输输入要终止的临时授权Token"); }

            using (var tran = new System.Transactions.TransactionScope())
            {
                var helper = DAL.DALFactory.Create();
                if (helper.IsSingle<Model.Token>(t => t.UserToken == userToken) == false)
                { throw new Exception("token不存在"); }
                var token = helper.GetSingle<Model.Token>(t => t.UserToken == userToken);
                if (token.OwnerAccount != this.Token.OwnerAccount)
                { throw new Exception("不能终止他人的临时授权"); }
                if (token.OwnerAccount == token.OperatorAccount)
                { throw new Exception("只能终止临时授权Token"); }
                if (token.ExpireTime < DateTime.Now)
                { throw new Exception("Token已过期，无需终止"); }
                token.ExpireTime = DateTime.Now.AddDays(-1);
                if (helper.Update<Model.Token>(token, t => t.Id == token.Id) !=1)
                { throw new Exception("终止临时授权失败"); }
                tran.Complete();
            }
        }
    }
}
